<?php
/**
 *
 * ============================================================================
 * * 版权所有 度拉拉 * *
 * 网站地址: http://www.dlltrip.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * Author By: 倪宗锋
 * PhpStorm WechatLogin.php
 * Create By 2017/6/8 10:46 $
 */

namespace common\service\login;


use common\models\ShUser;
use common\models\ShUserSystemAuth;
use common\util\CurlInterface;
use common\util\Util;

class WechatLogin
{


    /**
     * Des:非授权、静默登录
     * Name: getAuthLoginUrl
     * @param $showUrl
     * @return string
     * @author 倪宗锋
     */
    public  function getLoginUrlUnAuth($showUrl)
    {
        $WxPayConfig = Util::getWeChatConfig();
        $siteConfig = Util::getSiteConfig();
        $redirect_uri = $siteConfig['authLoginUrl'];
        $setLoginUrl = $siteConfig['host_name'] . $siteConfig['setLoginUrl'] . '&redirect=' . urlencode($showUrl);
        $urlObj["appid"] = $WxPayConfig['appid'];
        $urlObj["redirect_uri"] = $redirect_uri . '&redirect=' . urlencode($setLoginUrl);
        $urlObj["response_type"] = "code";
        $urlObj["scope"] = "snsapi_base";//授权登录
        $urlObj["state"] = rand(10, 99) . "#wechat_redirect";
        $bizString = http_build_query($urlObj);
        $url = $siteConfig['authorizeUrl'] . $bizString;
        return $url;
    }

    /**
     * Function Description:根据code获取token
     * Function Name: getToken
     * @param $code
     *
     * @return array
     *
     * @author 倪宗锋
     */
    public function getToken($code)
    {
        $WxPayConfig = Util::getWeChatConfig();
        $siteConfig = Util::getSiteConfig();
        $urlObj["appid"] = $WxPayConfig['appid'];
        $urlObj["secret"] = $WxPayConfig['appsecret'];
        $urlObj["code"] = $code;
        $urlObj["grant_type"] = "authorization_code";
        $bizString = http_build_query($urlObj);
        $url = $siteConfig['authTokenUrl'] . $bizString;
        $curlInterface = new CurlInterface('', 4);
        $curlInterface->setBaseUrl($url);
        $getToken = $curlInterface->execute('', 'GET');
        if (empty($getToken['openid'])) {
            return Util::returnArrEr('参数无效！');
        }
        return Util::returnArrSu('', $getToken);
    }

}